package com.homwee.factory.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.homwee.factory.R;
//import com.changhong.tvos.common.MiscManager;
//import com.changhong.tvos.common.TVManager;
//import com.changhong.tvos.common.exception.TVManagerNotInitException;
//zcj 2018-10-30 import com.changhong.tvos.service.TvMiscManager;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import android.util.Log;

public class VendorAppManager {
	static String FILE_VENDOR_XML ="/data/vendorapp/vendor.xml";
	static String FILE_APP_LIST ="/perm/preapp/vapplist";
	static String FILE_APP_PACKAGES ="/perm/preapp/vpackages";
	static String FILE_KEY_VENDOR ="/perm/preapp/keyvendor";

	static String NODE ="vendor";
	static String NODE_NAME ="name";
	static String NODE_IMPORT ="import";
	static String NODE_MODEL ="model";
	static String NODE_WILDCARD ="wildcard";
	static String NODE_APPLIST ="applist";
	static String NODE_EXTPATH ="extpath";
	static String NODE_DIRECTKEY ="directkey";
	
	static boolean ForTest =true;
	
	Context mContext;
	String mCurModel =null;
//	MiscManager mMiscManager =null;
	//zcj 2018-10-30 	TvMiscManager mTvMiscManager = null;
	List<VendorAppInfo> mVendorAppInfoList =new ArrayList<VendorAppInfo>();
	
	String mImport =null;
	String mAppPath ="/data/vendorapp/";
	
	public VendorAppManager(Context context){
		mContext =context;
		try {
//			mMiscManager =TVManager.getInstance(context).getMiscManager();
			mCurModel ="lcd";//mMiscManager.getCurProductType();//@@
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
//		File mFile =new File("/perm/preapp", "vpackages");
//		if(mFile.exists() ==false){
//			try {
//				mFile.createNewFile();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		InputStream mInputStream =null;
		try {
			mInputStream = new FileInputStream(FILE_VENDOR_XML);
			parseXML(mInputStream);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(mInputStream ==null){
			parseXML();
		}else{
			parseXML(mInputStream);
		}
		
		for(VendorAppInfo info :mVendorAppInfoList){
			info.init();
			if(ForTest || info.checkModel(mCurModel)){
				if(info.mExtPath !=null && info.mExtPath.length() >2){
					mAppPath =info.mExtPath;
				}else{
					mAppPath ="/data/vendorapp/";
				}
				copyAPK(info.mAppList);
				wirteInfos(FILE_APP_LIST ,info.mAppList);
				wirteInfos(FILE_APP_PACKAGES ,info.mPackageList);
				wirteInfos(FILE_KEY_VENDOR ,info.keyVendorInfos);
			}
		}
		
		
	}
	
	void parseXML(){
		Log.v("tv","parseXML");
		XmlResourceParser xrp =mContext.getResources().getXml(R.xml.vendor);
		VendorAppInfo mInfo =null;
		
		try {
            while (xrp.next() != XmlResourceParser.START_TAG)
                continue;
            xrp.next();
			while (xrp.getEventType() !=XmlResourceParser.END_DOCUMENT) {

				String nodeName =xrp.getName();
				
				if(xrp.getEventType() ==XmlResourceParser.START_TAG){
					if(NODE.equals(nodeName)){
						
						mInfo =new VendorAppInfo();

						for(int i=0;i<xrp.getAttributeCount();i++){
							String mName =xrp.getAttributeName(i);
							Log.v("tv","mName ="+mName);
							if(NODE_IMPORT.equals(mName)){
								mImport =xrp.getAttributeValue(i);
							}else if(NODE_NAME.equals(mName)){
								mInfo.mName =xrp.getAttributeValue(i);
								mVendorAppInfoList.add(mInfo);
							}else if(NODE_MODEL.equals(mName)){
								mInfo.mModel =xrp.getAttributeValue(i);
							}else if(NODE_WILDCARD.equals(mName)){
								mInfo.mWildCard =xrp.getAttributeValue(i);
							}else if(NODE_APPLIST.equals(mName)){
								mInfo.mApp =xrp.getAttributeValue(i);
							}else if(NODE_EXTPATH.equals(mName)){
								mInfo.mExtPath =xrp.getAttributeValue(i);
							}else if(NODE_DIRECTKEY.equals(mName)){
								mInfo.mDirectKey =xrp.getAttributeValue(i);
							}
						}

					}

				}else if(xrp.getEventType() ==XmlResourceParser.END_TAG){

				}
				xrp.next();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
	void parseXML(InputStream in){
		Log.v("tv","parseXML InputStream");
		XmlPullParserFactory factory =null;
		XmlPullParser xpp =null;

		try {

	        factory = XmlPullParserFactory.newInstance ();
	        factory.setNamespaceAware( true );
	        xpp = factory.newPullParser();
	        xpp.setInput(in,"UTF-8");
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		VendorAppInfo mInfo =null;
		
		try {
            while (xpp.next() != XmlResourceParser.START_TAG)
                continue;
            xpp.next();
			while (xpp.getEventType() !=XmlResourceParser.END_DOCUMENT) {

				String nodeName =xpp.getName();
				
				if(xpp.getEventType() ==XmlResourceParser.START_TAG){
					if(NODE.equals(nodeName)){
						
						mInfo =new VendorAppInfo();

						for(int i=0;i<xpp.getAttributeCount();i++){
							String mName =xpp.getAttributeName(i);
							Log.v("tv","mName ="+mName);
							
							if(NODE_IMPORT.equals(mName)){
								mImport =xpp.getAttributeValue(i);
							}else if(NODE_NAME.equals(mName)){
								mInfo.mName =xpp.getAttributeValue(i);
								mVendorAppInfoList.add(mInfo);
							}else if(NODE_MODEL.equals(mName)){
								mInfo.mModel =xpp.getAttributeValue(i);
							}else if(NODE_WILDCARD.equals(mName)){
								mInfo.mWildCard =xpp.getAttributeValue(i);
							}else if(NODE_APPLIST.equals(mName)){
								mInfo.mApp =xpp.getAttributeValue(i);
							}else if(NODE_EXTPATH.equals(mName)){
								mInfo.mExtPath =xpp.getAttributeValue(i);
							}else if(NODE_DIRECTKEY.equals(mName)){
								mInfo.mDirectKey =xpp.getAttributeValue(i);
							}
						}

					}

				}else if(xpp.getEventType() ==XmlResourceParser.END_TAG){

				}
				xpp.next();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
	String getPackageInfo(String filepath){
		String pkgName = null;
		PackageInfo pkgInfo = mContext.getPackageManager()
				.getPackageArchiveInfo(filepath, PackageManager.GET_ACTIVITIES);
		if (pkgInfo != null) {
			pkgName = pkgInfo.packageName;
		}
		return pkgName;
	}
	
	public boolean copyAPK(List<String> mAppList){
		boolean Err =false;
		Runtime mRuntime =Runtime.getRuntime();
		for(String mApp:mAppList){
			try {
				mRuntime.exec("cp "+mAppPath+mApp+" /data/app");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return Err;
		
	}
	
	void wirteInfos(String filePath,List<String> infos){
		try {
			OutputStream mOutputStream =new FileOutputStream(filePath ,true);
			for(String info:infos){
				if(info !=null){
					mOutputStream.write(info.getBytes());
					mOutputStream.write('\n');
				}
			}
			mOutputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.v("tv","wirteInfos FileNotFoundException");
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			Log.v("tv","wirteInfos IOException");
			e.printStackTrace();
		}

	}
	
	public class VendorAppInfo{
		String mName;
		String mModel;
		String mWildCard;
		String mApp;
		String mExtPath;
		String mDirectKey;
		
		List<String> mModelList =new ArrayList<String>();
		List<String> mAppList =new ArrayList<String>();
		List<String> mDirectKeyList =new ArrayList<String>();
		List<String> mPackageList =new ArrayList<String>(); 
		List<String> keyVendorInfos =new ArrayList<String>(); 
		
		public String toString(){
			return mName+" "+mModel+" "+mWildCard+" "+mApp+" "+mExtPath+" "+mDirectKey;
		}
		
		public boolean checkModel(String model){
			if(mModelList.size() >0){
				if(mModelList.indexOf(model) >=0){
					return true;
				}
			}else{
				Pattern pattern = Pattern.compile(mWildCard);
				Matcher matcher = pattern.matcher(model);
				if (matcher.matches()) {
					return true;
				}
			}

			return false;
		}
		
		public void init(){
			String VendorInfo ="vendor="+mName;
			String appInfo="applist=";
			String directKeyInfo="directkey=";
			
			if(mModel !=null){
				String [] mModels =mModel.split(" ");
				for(int i=0;i<mModels.length;i++){
					mModelList.add(mModels[i]);
				}
			}
			
			if(mApp!=null){
				String [] mApps =mApp.split(" ");
				
				for(int i=0;i<mApps.length;i++){
					mAppList.add(mApps[i]);
					appInfo =appInfo+" "+mApps[i];
					mPackageList.add(getPackageInfo(mAppPath+mApp));
				}
				
			}
			
			if(mDirectKey!=null){
				String [] mDirectKeys =mDirectKey.split(" ");
				
				for(int i=0;i<mDirectKeys.length;i++){
					mDirectKeyList.add(mDirectKeys[i]);
					directKeyInfo =directKeyInfo+" "+mDirectKeys[i];
				}
			}
			
			keyVendorInfos.add(VendorInfo);
			keyVendorInfos.add(appInfo);
			keyVendorInfos.add(directKeyInfo);
		}
	}
}
